package com.zg.autoflow.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zg.autoflow.service.AutoflowExtSelNextConfigService;
import com.zg.common.core.dao.autoflow.dao.AutoflowExtSelNextConfigDao;
import com.zg.common.core.dao.autoflow.dao.SettleBizformDao;
import com.zg.common.core.dao.autoflow.entity.AutoflowExtSelNextConfig;
import com.zg.common.core.dao.autoflow.entity.SettleBizform;
import com.zg.common.core.dao.autoflow.entity.SettleWorkflowInstance;
import lombok.RequiredArgsConstructor;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

/**
* @author zg
*/
@Service
@RequiredArgsConstructor
public class AutoflowExtSelNextConfigServiceImpl implements AutoflowExtSelNextConfigService {

    private final JdbcTemplate jdbcTemplate;
    private final SettleBizformDao settleBizformDao;
    private final AutoflowExtSelNextConfigDao autoflowExtSelNextConfigDao;

    @Override
    public AutoflowExtSelNextConfig findNextConfig(SettleWorkflowInstance prevFlowInst) {
        //查询前置流程的流转配置
        List<AutoflowExtSelNextConfig> selNextConfigList = autoflowExtSelNextConfigDao.list(
                new LambdaQueryWrapper<AutoflowExtSelNextConfig>()
                        .eq(AutoflowExtSelNextConfig::getPreFlowCode, prevFlowInst.getFlowCode())
                        .eq(AutoflowExtSelNextConfig::getIsUse, true)
        );
        if (CollUtil.isEmpty(selNextConfigList)) {
            return null;
        }
        for (AutoflowExtSelNextConfig config : selNextConfigList) {
            //对比流程实例中，对应的表单，字段的值和配置值是否一样

            List<SettleBizform> bizFormList = settleBizformDao.list(
                    new LambdaQueryWrapper<SettleBizform>()
                            .eq(SettleBizform::getFormModelCode, config.getFormCode())
                            .eq(SettleBizform::getInstCode, prevFlowInst.getInstCode())
                            .isNotNull(SettleBizform::getBizFormId)
                            .orderByDesc(SettleBizform::getCreateDate)
            );

            if (CollUtil.isEmpty(bizFormList)) {
                return null;
            }

            //取第一个表单的数据
            SettleBizform bizform = bizFormList.get(0);
            String sql = " select #1 from #2 where id = ? ";
            sql = StrUtil.replace(sql, "#1", config.getColumnCode());
            sql = StrUtil.replace(sql, "#2", bizform.getBizzTable());

            String result = jdbcTemplate.queryForObject(sql, String.class, bizform.getBizFormId());

            if (StrUtil.isNotBlank(result)
                    && result.equals(config.getColumnVal())) {
                return config;
            }
        }
        return null;
    }
}
